<template>
    <el-autocomplete 
    :value="value" 
    value-key="name" 
    placeholder="请输入至少3个关键词" 
    :fetch-suggestions="querySearchAsync" 
    @select="handleSelect" 
    @input="onChange" 
    @blur="blur" 
    @clear="clear">
    </el-autocomplete>
</template>

<script>
import {searchCompany} from "@/api/myCompany.js";
    export default {
        props:['value'],
        data() {
            return {
                options:[],
                timeout:  null,
            }
        },
       methods:{
        handleSelect(item){
           this.$emit('selectChange',item)
        },
         querySearchAsync(query,cb){
            if(query){
                clearTimeout(this.timeout);
                this.timeout = setTimeout(()=>{
                    searchCompany({Name:query.trim(),pageNum:1,pageSize:10}).then((res)=>{
                        this.options = res.result;
                        cb(res.result);
                    });
                    console.log(query)
                },200)
            }else{
                cb([]);
            }
        },
        blur() {
            clearTimeout(this.timeout);
            this.timeout = setTimeout(()=>{
                const data = this.options;
                this.$emit('blur')
                for (var i=0; i<data.length; i++) {
                   if(data[i].name === this.value.trim()) {
                       this.$emit('registered',true);
                       return;
                   } 
                }
                this.$emit('registered',false);
            },1000)
        }, 
        clear(){
            this.$emit('clear')
        },
        onChange(value){
            this.$emit('update:value', value);
        }
       } 
    }
</script>

<style scoped>

</style>